<?php

namespace App\Repository\UpThree;

use App\Api\CatchOrder\DouYin;
use App\Api\CatchOrder\Pdd;
use App\Api\Sms\SmsClient;
use App\Api\Transfer;
use App\Jobs\OrderSubmit;
use App\Repository\Admin\AdminUsersLogRepository;
use App\Repository\Admin\AdminUsersRepository;
use App\Repository\BaseRepository;
use App\Repository\CatchConf\DouYinRepository;
use App\Repository\CatchConf\PddRepository;
use App\Repository\Commit\DictDatarRepository;
use App\Repository\GetWay\WayRepository;
use App\Repository\Order\OrderChannelRepository;
use App\Repository\Order\OrderProductRepository;
use App\Repository\Orders\OrdersRepository;
use App\Repository\Product\GoodsRepository;
use App\Repository\Product\ProductRepository;
use App\Repository\Service\ServiceRepository;
use App\Repository\Sms\SmsConfRepository;
use App\Repository\Sms\SmsReplyRepository;
use App\Repository\Sms\SmsSendLogRepository;
use App\Repository\Sms\SmsTmpRepository;
use App\Repository\Zhuandan\GoodsZRepository;
use App\Repository\Zhuandan\SmsZRepository;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request as req;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

//use App\Repository\StockMain\GoodsOrderRepostition;

// 该model 12月份 弃用

class MainOrderRepostition extends BaseRepository
{
    private $goodsModel = null;
    private $productModel = null;
    private $orderProductModel = null;
    private $channelModel = null;
    private $orderModel = null;
    private $userMoneyLog = null;
    private $log = null;
    private $logOrder = null;
    private $orderKeys = null;
    private $orderKeysTime = null;
    private $smsZModle = null;
    private $goodsZModle = null;

    public function __construct()
    {
        $this->goodsModel = new GoodsRepository();
        $this->productModel = new ProductRepository();
        $this->orderProductModel = new OrderProductRepository();
        $this->channelModel = new OrderChannelRepository();
        $this->orderModel = new OrdersRepository();
        $this->userMoneyLog = new AdminUsersLogRepository();
        $this->smsZModle = new SmsZRepository();
        $this->goodsZModle = new GoodsZRepository();
        $this->log = new Logger('ChinnelLog');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/ChinnelLog.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        // 记录的是 第三方成功了 但是本地失败了
        $this->logOrder = new Logger('orderLogs');
        $this->logOrder->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/orderLogs.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
        $this->orderKeys = '';
        $this->orderKeysTime = 5; //缓存多长时间
    }

    // 查询号码
    public function selectNum($data = array())
    {
    }

    // 下单统一调用接口
    public function orderSubmit($data = array())
    {
        // var_dump(time());
        if (empty($data['goods_id']) && (empty($data['goods_code']) || empty($data['shop_id']))) {
            return $this->returnMsg(10001, '商品信息不能为空');
        }
        if (empty($data['name'])) {
            return $this->returnMsg(1, '用户名不能为空');
        }
        $name = strip_tags(trim($data['name']));
        $len = mb_strlen($name);
        if (!preg_match('/^[\x{4e00}-\x{9fa5}]+[·?]?[\x{4e00}-\x{9fa5}]+$/u', $name, $matchers)) {
            return $this->returnMsg(10006, '用户名只能是两个及两个以上汉字');
        }
        if ($len < 2 || $len > 100) {
            return $this->returnMsg(10006, '用户名只能是两个及两个以上汉字');
        }

        //判断手机号
        if (empty($data['contact'])) {
            return $this->returnMsg(10007, '请输入您的手机号码');
        }
        if (!preg_match("/^1[3456789]\d{9}$/", $data['contact'])) {
            return $this->returnMsg(10007, '手机号错误，请重新查看');
        }
        if (empty($data['province'])) {
            return $this->returnMsg(10010, '缺少省份');
        }
        if (empty($data['city'])) {
            return $this->returnMsg(10011, '缺少市');
        }
        // if (!$request->has('area')) {
        //     return $this->returnMsg(10012, '缺少区');
        // }

        // $province = strip_tags(trim($data['province']));
        // $city = strip_tags(trim($data['city']));


        if (empty($data['address'])) {
            return $this->returnMsg(10013, '详细地址不能为空');
        }
        $lens = mb_strlen($data['address']);
        if (getStrLen($data['address']) < 2 || $lens > 80) {
            return $this->returnMsg(10006, '详细地址内容不小于2个汉字大于80个汉字，请重新输入');
        }
        // 提交过来的字符串处理
        if (!empty($data['identity'])) {
            $data['identity'] = strtoupper(trim($data['identity'], ' '));
        }
        if (!empty($data['identity'])) {
            if (strlen($data['identity']) != 18) {
                return $this->returnMsg(10006, '请输入正确的身份证号');
            }
        }
        $data['address'] = (trim($data['address'], ' '));
        $data['contact'] = (trim($data['contact'], ' '));
        $data['name'] = (trim($data['name'], ' '));
        $params['address'] = $data['address'];
        // 身份信息的验证
        // if (empty($data['identity'])) {
        //     return $this->returnMsg(10007, '身份证号码位数不正确，请检查');
        // }
        $idcard = !empty($data['identity']) ? $data['identity'] : '';
        //if (empty($data['identity'])) {
        //     return $this->returnMsg(10007, '身份证号码位数不正确，请检查');
        // }
        // if (!is_idcard($idcard)) {
        //     return $this->returnMsg(10007, '身份证号码不正确，请检查');
        // }

        $goods_codeCache = '';
        if (!empty($data['goods_code'])) {
            $goods_codeCache = $data['goods_code'];
        }
        $shop_idCache = '';
        if (!empty($data['shop_id'])) {
            $shop_idCache = $data['shop_id'];
        }
        $goods_idCache = '';
        if (!empty($data['goods_id'])) {
            $goods_idCache = $data['goods_id'];
        }
        $this->orderKeys = $idcard . '_' . $data['contact'] . '_' . $goods_idCache . '_' . $goods_codeCache . '_' . $shop_idCache;
        // 使用缓存防止重复提交 或 重复记录数据
        // $resCache = Cache::get($idcard . '_' . $data['contact']);
        $resCache = Cache::get($this->orderKeys);
        // $oneAdress = Cache::get($idcard . '_' . $data['contact'] . '_address');
        // $oneAdress = Cache::get($this->orderKeys . '_address');
        if (!empty($resCache) && ($resCache == $data['address'])) {
            if ($resCache == $data['address']) {
                return $this->returnMsg(101, '请稍后提交');
            }
            // return  $this->returnMsg(102, $resCache);
        }
        // 防止重复提交

        $getRepeat = Cache::get($this->orderKeys . '_repeat');
        if (!empty($getRepeat) && $getRepeat == 1) {
            return $this->returnMsg(102, '提交中,请稍后重新提交');
        }
        Cache::put($this->orderKeys . '_repeat', 1, Carbon::now()->addMinutes($this->orderKeysTime));
        $isTrueSuccess = Cache::get($this->orderKeys . '_success');
        // var_dump($this->orderKeys . '_success', 1111111111);
        // var_dump($isTrueSuccess, 222222222);
        if (!empty($isTrueSuccess)) {
            return $this->returnMsg(103, '您已提交成功');
        }
        $errorNums = Cache::get($this->orderKeys . '_error');
        // 提交10次错误信息后 直接提示失败
        if ($errorNums >= 10) {
            return $this->returnMsg(105, '请稍后提交');
        }
        if (empty($errorNums)) {
            $errorNums = 0;
        }
        $errorNums++;
        Cache::put($this->orderKeys, $data['address'], Carbon::now()->addMinutes($this->orderKeysTime));
        // 订单号的处理
        $data['orderno'] = !empty($data['dist_orderno']) ? ('HK_' . $data['dist_orderno']) : creatOrderNums('HK_');
        // if (!empty($data['dist_orderno'])) {
        // }
        // 判断订单号是否存在
        $whereIsOrderNo = [
            'ordersno' => $data['orderno'],
        ];
        $isOrder = $this->orderModel->getOne($whereIsOrderNo);
        if (!empty($isOrder)) {
            return $this->returnMsg(1002, '您的订单已存在,请前去更改');
        }
        // 参数验证完了
        $msg = '未查询到下单';
        $flag = true;
        //商品验证
        $whereGoods = [
            'status' => 0,
        ];
        if (!empty($data['goods_id'])) {
            $whereGoods['id'] = $data['goods_id'];
        }
        if (!empty($data['goods_code']) && !empty($data['shop_id'])) {
            $whereGoods['goods_code'] = $data['goods_code'];
            $whereGoods['shop_id'] = $data['shop_id'];
        }
        // var_dump($whereGoods);
        $isValid = true;
        // DB::connection()->enableQueryLog();
        $resGoods = $this->goodsModel->getOne($whereGoods, ['id', 'name', 'goods_code', 'passing_money', 'author_commission', 'product_name', 'product_id', 'product_code', 'shop_str', 'sup_goods_id_str', 'sup_shop_name', 'sup_shop_id', 'sup_goods_id', 'sup_goods_name', 'shop_id_str', 'shop_name_str', 'shop_id', 'shop_name', 'goods_price', 'goods_point', 'main_pic', 'is_trun']);
        $resGoods = json_decode(json_encode($resGoods), true);
        // $log = DB::getQueryLog();
        // var_dump($log);
        if (!$resGoods) {
            $flag = false;
            $msg = '未查询到商品信息';
            return $this->returnMsg(100, '未查询到商品信息');
        }
        if (empty($data['shop_id'])) {
            $data['shop_id'] = $resGoods['shop_id'];
        }
        $insertData = [];
        if ($flag) {
            // 添加还是修改 为了存储信息
            $insertData = [
                'xh_member_id' => $data['xh_member_id'] ?? 0,
                'is_api_number' => $data['is_api_number'] ?? 1,
                'orderno' => $data['orderno'],
                'dist_orderno' => !empty($data['dist_orderno']) ? $data['dist_orderno'] : '',
                'dist_id' => !empty($data['dist_id']) ? $data['dist_id'] : 0,
                'dist_name' => !empty($data['dist_name']) ? $data['dist_name'] : '',
                'contact_phone' => !empty($data['contact_phone']) ? $data['contact_phone'] : $data['contact'],
                'contact_name' => !empty($data['contact_name']) ? $data['contact_name'] : $data['name'],
                'pay_name' => $data['name'],
                'pay_phone' => $data['contact'],
                'pay_identity' => $idcard,
                'iccid' => !empty($data['number']) ? $data['number'] : '',
                'province' => !empty($data['numberProvince']) ? $data['numberProvince'] : '',
                'city' => !empty($data['numberCity']) ? $data['numberCity'] : '',
                'post_province' => !empty($data['province']) ? $data['province'] : '',
                'post_city' => !empty($data['city']) ? $data['city'] : '',
                'post_area' => !empty($data['area']) ? $data['area'] : '',
                'post_address' => !empty($data['address']) ? $data['address'] : '',
                'author_id' => !empty($data['author_id']) ? $data['author_id'] : '',
                'author_name' => !empty($data['author_name']) ? $data['author_name'] : '',
                'card_num' => !empty($data['card_num']) ? $data['card_num'] : '',
                'remark' => !empty($data['remark']) ? $data['remark'] : '',
                'status' => $data['status'] ?? 0,
                'shop_id' => $data['shop_id'] ?? 0,
                'author_commission' => $resGoods['author_commission'] ?? 0,
                'passing_money' => $resGoods['passing_money'] ?? 0,
                'shop_str' => $resGoods['shop_str'],
                'goods_id' => $resGoods['id'],
                'goods_name' => $resGoods['name'],
                'goods_code' => $resGoods['goods_code'],
                'product_id' => $resGoods['product_id'],
                'product_name' => $resGoods['product_name'],
                'product_code' => $resGoods['product_code'],
                'sup_goods_name' => $resGoods['sup_goods_name'],
                'shop_id_str' => $resGoods['shop_id_str'],
                'shop_name_str' => $resGoods['shop_name_str'],
                'sup_goods_id' => $resGoods['sup_goods_id'],
                'sup_goods_id_str' => $resGoods['sup_goods_id_str'],
                'sup_shop_id' => $resGoods['sup_shop_id'],
                'sup_shop_name' => $resGoods['sup_shop_name'],
                'source' => !empty($data['source']) ? $data['source'] : 0,
                'shop_name' => !empty($resGoods['shop_name']) ? $resGoods['shop_name'] : 0,
                'sell_name' => !empty($data['sell_name']) ? $data['sell_name'] : '',
                'is_trun' => !empty($resGoods['is_trun']) ? $resGoods['is_trun'] : 0,
                'pay_money' => !empty($data['money']) ? $data['money'] : $resGoods['goods_price'],
                'product_type' => !empty($resGoods['product_type']) ? $resGoods['product_type'] : '',
                'product_operator' => !empty($resGoods['product_operator']) ? $resGoods['product_operator'] : 0,
                'sku_number' => $data['sku_number'] ?? '',
                'sku_area' => $data['sku_area'] ?? '',
                'package_name' => $data['package_name'] ?? '',
                'number_remark' => !empty($data['number_remark']) ? $data['number_remark'] : '',
            ];
//            sku靓号的分析
            if (isset($data['package_name'])) {
                preg_match('/([0-9]{11,13})/', $data['package_name'], $tmp);
                if (!empty($tmp)) {
                    $insertData['sku_number'] = $tmp[1];
                    $insertData['is_api_number'] = 1;
                }
            }
        }
        // 产品验证开始
        $productId = !empty($resGoods['product_id']) ? $resGoods['product_id'] : 0;
        // var_dump($productId, 222222222);

        if (empty($resGoods['product_id']) || empty($resGoods['product_code'])) {
            if (empty($resGoods['sup_goods_id_str'])) {
                $isValid = false;
                $msgs = '商品出错,请联系管理员';
                // return $this->returnMsg(16, '商品出错,请联系管理员');
            }
            if ($isValid) {
                $productArr = explode('.', $resGoods['sup_goods_id_str']);
                if (empty($productArr[1])) {
                    $isValid = false;
                    $msgs = '该产品无法下单,请联系商家';
                    // return $this->returnMsg(17, '该产品无法下单,请联系商家');
                }
            }

            if ($isValid) {
                $disGoods = $this->goodsModel->getOne(['id' => $productArr[1]], ['id', 'name', 'goods_code', 'product_name', 'product_id', 'product_code', 'shop_str', 'sup_goods_id_str', 'status']);
                $disGoods = json_decode(json_encode($disGoods), true);
                if (empty($disGoods['product_id'])) {
                    $isValid = false;
                    $msgs = '该产品无法下单,请联系商家';
                    // return $this->returnMsg(18, '请联系供应商,未查询到产品信息');
                }
                if (!empty($disGoods['status']) && $disGoods['status'] == 1) {
                    $isValid = false;
                    $msgs = '该产品无法下单,请联系商家';
                    // return $this->returnMsg(19, '该产品已下架,请联系运营商');
                }
                if ($isValid) {
                    $productId = $disGoods['product_id'];
                    $insertData['product_id'] = $disGoods['product_id'];
                    $insertData['product_name'] = $disGoods['product_name'];
                    $insertData['product_code'] = $disGoods['product_code'];
                }
            }
        }

        if ($flag) {
            $resProduct = $this->validProduct($productId, $data);
            // var_dump($resProduct);
            $isProduct = true;
            if (empty($resProduct['code']) || $resProduct['code'] != 200) {
                // $flag = false;
                $isValid = false;
                $isProduct = false;
                $msgs = $msg = !empty($resProduct['msg']) ? $resProduct['msg'] : '产品效验未过';
                // $insertData['status'] = 50;
                // $insertData['three_msg'] = !empty($resProduct['msg']) ? $resProduct['msg'] : '产品效验未过';
            }
            // 多次开卡问题  同一张卡多次提交
            if (!empty($resProduct['code']) && $resProduct['code'] == 10000) {
                $flag = false;
                $isProduct = false;
                $msg = !empty($resProduct['msg']) ? $resProduct['msg'] : '产品效验未过';
            }
            if (!$isProduct) {
                // var_dump($msg, 11111111);
                Cache::put($this->orderKeys . '_repeat', 2, Carbon::now()->addMinutes($this->orderKeysTime));
                // 防止用户长时间提交
                Cache::put($this->orderKeys . '_error', $errorNums, Carbon::now()->addDay(1));
                return $this->returnMsg(100, $msg);
            }
            // $insertData['sup_orderno'] = !empty($resProduct['data']['order_id']) ? $resProduct['data']['order_id'] : ''; //渠道单号
            // $insertData['sup_id'] = !empty($resProduct['data']['channel_id']) ? $resProduct['data']['channel_id'] : ''; //渠道id
            // $insertData['sup_name'] = !empty($resProduct['data']['channel_name']) ? $resProduct['data']['channel_name'] : ''; //渠道名称
            // $insertData['three_msg'] = !empty($resProduct['data']['msg']) ? $resProduct['data']['msg'] : '';
            // $insertData['channel_error_josn'] = !empty($resProduct['data']['error']) ? $resProduct['data']['error'] : '';
        }
        if (!$isValid) {
            $insertData['status'] = 50;
            $insertData['three_msg'] = !empty($msgs) ? $msgs : '产品效验未过';
        }
        if (!$flag) {
            $flag = true;
            $insertData['status'] = 50;
            $insertData['three_msg'] = !empty($msg) ? $msg : '效验未过';
        }
        // 下单流程

        $resOrder = $this->orderModel->add($insertData);
//        $this->logOrder->info('参数:' . json_encode($insertData) . '返回参数:' . jsonEncodeMsg($resOrder));
        if (empty($resOrder['code']) || $resOrder['code'] != 200) {
            //第三方提交成功了 但是存储数据库的时候 失败了 记录日志文件方便查看
            $this->logOrder->info('参数:' . json_encode($insertData) . '返回参数:' . jsonEncodeMsg($resOrder));
        }

        Cache::put($this->orderKeys . '_repeat', 2, Carbon::now()->addMinutes($this->orderKeysTime));
        // var_dump(time());
        if ($flag) {
            // 添加到队列中
            Cache::put($this->orderKeys . '_success', '您已下过单,请更新信息在下单', Carbon::now()->addMinutes(60));
            return $this->returnMsg(200, '下单成功', [
                'order' => $insertData['dist_orderno'],
                'order_num' => $insertData['orderno'],
                'money' => !empty($resGoods['goods_price']) ? $resGoods['goods_price'] * 100 : 0,
                'goods_name' => !empty($resGoods['name']) ? $resGoods['name'] : '',
                'goods_point' => !empty($resGoods['goods_point']) ? $resGoods['goods_point'] : '',
                'goods_id' => !empty($resGoods['id']) ? $resGoods['id'] : '',
                'goods_url' => !empty($resGoods['main_pic']) ? $resGoods['main_pic'] : '',
            ]);
        }
        // 防止用户长时间提交
        Cache::put($this->orderKeys . '_error', $errorNums, Carbon::now()->addDay(1));
        return $this->returnMsg(100, $msg);
    }

//我修改的直接提交修改订单到上游
    public function directOrderToThree($where = array(), $willEditData = [])
    {
        // 查询订单数据
        $resOrder = $this->orderModel->getOne($where);
        if (!empty($willEditData)) {
            $resOrder = array_merge($resOrder, $willEditData);
        }
        if (!$resOrder) {
            return $this->returnMsg(103, '查询失败');
        }
        if (!empty($resOrder['status']) && $resOrder['status'] == 1) {
            return $this->returnmsg(109, '该订单已提交,不能重复提交');
        }
//        if (!empty($resOrder['status']) && $resOrder['status'] <= 40) {
//            return $this->returnmsg(110, '该订单已提交过,请勿重复提交');
//        }
        if (!empty($resOrder['ordersno'])) {
            $isTrueSuccess = Cache::get($resOrder['ordersno'] . '_isTransfermain');
            if (!empty($isTrueSuccess) && $isTrueSuccess == 1) {
                return $this->returnmsg(1, '请五分钟后提交');
            }
            Cache::put($resOrder['ordersno'] . '_isTransfermain', 1, 300);
        }

        // 扣除用户的费用
//        $resDeduct = $this->deductExpen($resOrder, $resOrder['shop_id_str'], 1);
//        if (empty($resDeduct['code']) || $resDeduct['code'] != 200) {
//            $this->log->info('扣费失败的订单' . json_encode($resOrder) . '返回的结果:' . jsonEncodeMsg($resDeduct));
//            // return $this->returnMsg(106, '扣费失败');
//        }

        $whereProduct = [
            'id' => $resOrder['product_id'],
        ];
        // var_dump($whereProduct);
        $resProduct = $this->productModel->getOne($whereProduct);
        if (!$resProduct) {
            if (!empty($resOrder['ordersno'])) {
                Cache::put($resOrder['ordersno'] . '_isTransfermain', 0, 300);
            }
            return $this->returnMsg(104, '未查询到商品信息');
        }
//        if ($resProduct->is_product == 1) {
//            if (!empty($resOrder['ordersno'])) {
//                Cache::put($resOrder['ordersno'] . '_isTransfermain', 0, Carbon::now()->addMinutes(5));
//            }
//            return $this->returnMsg(105, '未开启自动生产');
//        }
        $productCode = $resProduct->product_code;
//        $this->log->info('渠道参数' . jsonEncodeMsg($resOrder));
        if ($resProduct->product_code == 1) {
            $productCode = $resOrder['goods_code'];
        }
        $channelData = [
            'product_code' => $productCode,
            'product_id' => $resProduct->id,
            'is_charm' => $resProduct->is_charm,
            'shop_id' => $resProduct->shop_id,
        ];
//        直接提交接口要的参数
//        $submitData = [
//            'post_province',
//            'post_city',
//            'post_area',
//            'channel_code',
//            'orderno',
//            'pay_name',
//            'pay_identity',
//            'pay_phone',
//            'channel_code',
//            'numberProvince',
//            'numbercity',
//            'iccid'
//        ];
//        $returnMsg = $this->orderSubmitThree('orderSubmit', $submitData);
        $resChannel = $this->moreChannel($channelData, $resOrder, true);
        if (!empty($resChannel['code']) && $resChannel['code'] == 10000) {
            if (!empty($resOrder['ordersno'])) {
                Cache::put($resOrder['ordersno'] . '_isTransfermain', 0, 300);
            }
            return $this->returnMsg(200, '未配置或未上架产品通道');
        }
        if (!empty($resChannel['code']) && $resChannel['code'] == 20000) {
            if (!empty($resOrder['ordersno'])) {
                Cache::put($resOrder['ordersno'] . '_isTransfermain', 0, 300);
            }
            // 渠道提交完了 得商品转单
            $goodsZRes = $this->isGoodsProduct($resOrder);
            // var_dump($goodsZRes);
            return $this->returnMsg(200, '渠道提交完了到末尾了');
        }
        $status = 1;
        if (empty($resChannel['code']) || $resChannel['code'] != 200) {
            // 这个地方可以重新提交 这个地方可以后面在提交
            $status = 60;
//            // 判断是否是异常单  比如报错或什么信息就是异常单
//            if (!empty($resChannel['data']['is_anb'])) {
//                // $status = 50;
//            }
        }
        if (!empty($resChannel['data']['real_name_url']) && $status != 60) {
            $status = 3;
        }


        $editData = $willEditData;
        $editData['status'] = $status;
        $editData['real_name_url'] = !empty($resChannel['data']['real_name_url']) ? $resChannel['data']['real_name_url'] : '';
        $editData['sup_orderno'] = !empty($resChannel['data']['order_id']) ? $resChannel['data']['order_id'] : '0'; //渠道单号
        $editData['iccid'] = !empty($resChannel['data']['iccid']) ? $resChannel['data']['iccid'] : '0'; //选择的手机号
        $editData['sup_id'] = !empty($resChannel['data']['channel_id']) ? $resChannel['data']['channel_id'] : '0'; //渠道id
        $editData['sup_name'] = !empty($resChannel['data']['channel_name']) ? $resChannel['data']['channel_name'] : '0'; //渠道名称
        $editData['three_msg'] = !empty($resChannel['data']['msg']) ? $resChannel['data']['msg'] : (!empty($resChannel['msg']) ? $resChannel['msg'] : '');
        $editData['channel_error_josn'] = !empty($resChannel['data']['error']) ? $resChannel['data']['error'] : '';

        // var_dump($editData);
        $resData = $this->editOrderThree($where, $editData);
//        $this->log->info("测试4:" . json_encode($resData));
        if (!empty($resOrder['ordersno'])) {
            Cache::put($resOrder['ordersno'] . '_isTransfermain', 0, 300);
        }
        //        提交后的状态来分配客服
        $RepositoryService = new ServiceRepository();
        $RepositoryService->statusBindServiceUser($resOrder['ordersno'], $resOrder['contact_phone'] ?? '', $resOrder['pay_identity'] ?? '');
        return $resData;
    }

    /**
     * 提交数据到第三方
     * where 查询条件
     * isTrue 是否只提交当前渠道  false 提交所有的渠道 true 提交当前渠道
     * isHand 是否是手动提交  false 自动提交 true 手动提交
     */
    public function orderThree($where = array(), $isTrue = false, $isHand = false)
    {
        // 查询订单数据
        $resOrder = $this->orderModel->getOne($where);

        // var_dump($resOrder);
        if (!$resOrder) {
            return $this->returnMsg(103, '查询失败');
        }
        if (!empty($resOrder['status']) && $resOrder['status'] == 1) {
            return $this->returnmsg(109, '该订单已提交,不能重复提交');
        }
        if (!empty($resOrder['status']) && $resOrder['status'] <= 40) {
            return $this->returnmsg(110, '该订单已提交过,请勿重复提交');
        }
        if (!empty($resOrder['ordersno'])) {
            $isTrueSuccess = Cache::get($resOrder['ordersno'] . '_isTransfermain');
            if (!empty($isTrueSuccess) && $isTrueSuccess == 1) {
                return [
                    'code' => 500,
                    'msg' => '请五分钟后提交',
                    'data' => [
                        'msg' => '请五分钟后提交'
                    ]
                ];
            }
            Cache::put($resOrder['ordersno'] . '_isTransfermain', 1, Carbon::now()->addMinutes(5));
        }
        // 扣除用户的费用
        $resDeduct = $this->deductExpen($resOrder, $resOrder['shop_id_str'], 1);
        if (empty($resDeduct['code']) || $resDeduct['code'] != 200) {
            $this->log->info('扣费失败的订单' . json_encode($resOrder) . '返回的结果:' . jsonEncodeMsg($resDeduct));
            // return $this->returnMsg(106, '扣费失败');
        }

        $whereProduct = [
            'id' => $resOrder['product_id'],
        ];
        // var_dump($whereProduct);
        $resProduct = $this->productModel->getOne($whereProduct);
        if (!$resProduct) {
            if (!empty($resOrder['ordersno'])) {
                Cache::put($resOrder['ordersno'] . '_isTransfermain', 0, Carbon::now()->addMinutes(5));
            }
            return $this->returnMsg(104, '未查询到商品信息');
        }
//        0:自动生产,1:手动生产,2:不生产
        if (false === $isHand && $resProduct->is_product >= 1) {
            if (!empty($resOrder['ordersno'])) {
                Cache::put($resOrder['ordersno'] . '_isTransfermain', 0, Carbon::now()->addMinutes(5));
            }
            return $this->returnMsg(105, '未开启自动生产:' . $resProduct->is_product);
        }
        $productCode = $resProduct->product_code;
        $this->log->info('渠道参数' . jsonEncodeMsg($resOrder));
        if ($resProduct->product_code == 1) {
            $productCode = $resOrder['goods_code'];
        }
        $channelData = [
            'product_code' => $productCode,
            'product_id' => $resProduct->id,
            'is_charm' => $resProduct->is_charm,
            'shop_id' => $resProduct->shop_id,
        ];
        $this->log->info('多通道参数' . jsonEncodeMsg($channelData));
        $resChannel = $this->moreChannel($channelData, $resOrder, $isTrue);
        if (!empty($resChannel['code']) && $resChannel['code'] == 10000) {
            if (!empty($resOrder['ordersno'])) {
                Cache::put($resOrder['ordersno'] . '_isTransfermain', 0, Carbon::now()->addMinutes(5));
            }
            return $this->returnMsg(200, '未配置或未上架产品通道');
        }
        if (!empty($resChannel['code']) && $resChannel['code'] == 20000) {
            if (!empty($resOrder['ordersno'])) {
                Cache::put($resOrder['ordersno'] . '_isTransfermain', 0, Carbon::now()->addMinutes(5));
            }
            // 渠道提交完了 得商品转单
            $goodsZRes = $this->isGoodsProduct($resOrder);
            // var_dump($goodsZRes);
            return $this->returnMsg(200, '渠道提交完了到末尾了');
        }
        $status = 1;
        if (empty($resChannel['code']) || $resChannel['code'] != 200) {
            // 这个地方可以重新提交 这个地方可以后面在提交
            $status = 60;
            // 判断是否是异常单  比如报错或什么信息就是异常单
            if (!empty($resChannel['data']['is_anb'])) {
                // $status = 50;
            }
            // $editData = [
            //     'status' => $status,
            //     'three_msg' =>  !empty($resChannel['msg']) ? $resChannel['msg'] : '未知错误,请联系管理员',
            // ];
            // $editData['sup_orderno'] = !empty($resChannel['data']['order_id']) ? $resChannel['data']['order_id'] : ''; //渠道单号
            // $editData['sup_id'] = !empty($resChannel['data']['channel_id']) ? $resChannel['data']['channel_id'] : ''; //渠道id
            // $editData['sup_name'] = !empty($resChannel['data']['channel_name']) ? $resChannel['data']['channel_name'] : ''; //渠道名称
            // $editData['channel_error_josn'] = !empty($resChannel['data']['error']) ? $resChannel['data']['error'] : '';
            // $this->editOrderThree($where, $editData);
            // return $this->returnMsg(105, !empty($resChannel['msg']) ? $resChannel['msg'] : '提交失败');
        }
        if (!empty($resChannel['data']['real_name_url']) && $status != 60) {
            $status = 3;
        }
        $editData = [
            'status' => $status,
        ];
        $editData['real_name_url'] = !empty($resChannel['data']['real_name_url']) ? $resChannel['data']['real_name_url'] : '';
        $editData['sup_orderno'] = !empty($resChannel['data']['order_id']) ? $resChannel['data']['order_id'] : '0'; //渠道单号
        if (!empty($resChannel['data']['iccid'])) {
            $editData['iccid'] = !empty($resChannel['data']['iccid']) ? $resChannel['data']['iccid'] : '0'; //选择的手机号
        }
        if (!empty($resChannel['data']['number_remark'])) {
            $editData['number_remark'] = !empty($resChannel['data']['number_remark']) ? $resChannel['data']['number_remark'] : ''; //选择的手机号
        }
        $editData['sup_id'] = !empty($resChannel['data']['channel_id']) ? $resChannel['data']['channel_id'] : '0'; //渠道id
        $editData['sup_name'] = !empty($resChannel['data']['channel_name']) ? $resChannel['data']['channel_name'] : '0'; //渠道名称
        $editData['three_msg'] = !empty($resChannel['data']['msg']) ? $resChannel['data']['msg'] : (!empty($resChannel['msg']) ? $resChannel['msg'] : '');
        $editData['channel_error_josn'] = !empty($resChannel['data']['error']) ? $resChannel['data']['error'] : '';
        // var_dump($editData);
        $resData = $this->editOrderThree($where, $editData);
        if (!empty($resOrder['ordersno'])) {
            Cache::put($resOrder['ordersno'] . '_isTransfermain', 0, Carbon::now()->addMinutes(5));
        }
        return $resData;
    }

    public function batchAllOrderThree($where = array())
    {
        $wheres = [];
        if (!empty($where['orderno'])) {
            $wheres = [
                'orderno' => !empty($where['orderno']) ? $where['orderno'] : '',
            ];
        }
        if (!empty($where['ordersno'])) {
            $wheres = [
                'ordersno' => !empty($where['ordersno']) ? $where['ordersno'] : '',
            ];
        }
        if (!empty($where['dist_orderno'])) {
            $wheres = [
                'dist_orderno' => !empty($where['dist_orderno']) ? $where['dist_orderno'] : '',
            ];
        }
        if (empty($wheres)) {
            return $this->returnMsg(101, '请传递查询条件');
        }
        return $this->orderThree($wheres, true);
    }

    /**
     * 订单状态的修改
     * @param [type] $where  订单查询的信息
     * @param [type] $data   订单修改的信息
     * @return void
     */
    public function editOrderThree($where, $data, $isChannel = true)
    {
        if (isset($data['orderno'])) {
            unset($data['orderno']);
        }
        if (empty($data['sup_id'])) {
            unset($data['sup_id']);
        }
        // var_dump($where, 22222222);
        // $this->log->info('数据订单后续bug5' . json_encode($where) . '数据修改' . json_encode($data));
        $res = $this->orderModel->editThree($where, $data, $isChannel);
        $this->log->info('修改订单条件' . jsonEncodeMsg($where) . '参数:' . jsonEncodeMsg($data) . '返回结果' . jsonEncodeMsg($res));
        // if (empty($data['status']) || $data['status'] <= 50) {
        // var_dump($res, 1111111);
        // }
        $orders = !empty($where['orderno']) ? $where['orderno'] : (!empty($res['data']['orderno']) ? $res['data']['orderno'] : '');
        if (!empty($orders)) {
            dispatch(new OrderSubmit($orders, 'smsAndPushOrder', 60 * 5))->onQueue('TaskOrderSubmitDispose');
        }


        return $res;
    }

    // 判断是否发送短信  和判断是否推送消息
    public function isSmsAndPush($where = [])
    {
        $resOrder = $this->orderModel->getOne($where);
        // var_dump($resOrder, 555555555);
        if (!$resOrder) {
            return $this->returnMsg(103, '查询失败');
        }
        // 判断订单是否需要重新提交
        $this->log->info('后续状态记录处理1015' . jsonEncodeMsg($resOrder));
        $res = [];
        // 判断是否推送信息
//        if ($resOrder['source'] == '5') {
//        }
        switch ($resOrder['source']) {
            case 1:
                // break;
                // if ($resOrder['sup_name'] != '广东电信') {
                //     break;
                // }
                // 抖音的发货 和 审核
                if ($resOrder['status'] >= 20 && $resOrder['status'] <= 40) {
                    // 查看抖音订单
                    // 只走 抖音发货成功的
                    $res['douyin'] = $this->douYinSendDeliver($resOrder, false);
                } else {
                    // $res['douyin'] = $this->douYinSendDeliver($resOrder, false, true);
                }
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                break;
            case 5:
                // 需要推送消息
                $res['pushmessage'] = $this->pushMessage($resOrder, false);
                break;
            case 6:
                if ($resOrder['status'] >= 20 && $resOrder['status'] <= 40) {
                    // 查看抖音订单
                    // 只走 抖音发货成功的
                    $res['douyin'] = $this->douYinSendDeliver($resOrder, false);
                } else {
                    // $res['douyin'] = $this->douYinSendDeliver($resOrder, false, true);
                }
                break;
            case 7:
                // 推送到感叹号

//                $res['pushganmessage'] = $this->pushGanMessage($resOrder, false);

                break;
            case 11:
//                if ($resOrder['status'] >= 20) {
//                    $res['pdd'] = $this->sendPddComPany($resOrder, false);
//                }
                break;
            case 15:
//                $modelInfor = new GoodsOrderRepostition();
//                $res['information'] = $modelInfor->syncOrdersStatus($resOrder);
        }
        // 判断是否发送短信  转单短信 暂时不用了 2023/02/14 12:11
        // if ($resOrder['nums'] > 1) {
        //     // 转单短信
        //     $res['sms'] = $this->isSmsProduct($resOrder, false);
        // } else {
        //     // 不是转单的短信
        //     $res['sms'] = $this->isSms($resOrder, false);
        // }
        // 统一按照之前的发送
        $res['sms'] = $this->isSms($resOrder, false);

        return $res;
    }
    // 推送消息

    /**
     * Undocumented function
     *
     * @param [type] $orderData
     * @param boolean $isTrue
     * @param boolean $isFail 是否发货 true 不发货 false 发货
     * @return void
     */
    public function douYinSendDeliver($orderData, $isTrue = true, $isFail = false, $isArt = true)
    {
        if ($isTrue) {
            if (!empty($orderData['orderno'])) {
                $where = ['orderno' => $orderData['orderno']];
            }
            if (!empty($orderData['dist_orderno'])) {
                $where = ['dist_orderno' => $orderData['dist_orderno']];
            }
            if (!empty($orderData['ordersno'])) {
                $where = ['ordersno' => $orderData['ordersno']];
            }
            $orderData = $this->orderModel->getOne($where);
        }
        // $this->log->info('抖音审核订单处理:' . json_encode($where));
        // if ($orderData['status'] != 20) {
        //     return $this->returnMsg(3, '该状态不在提交中');
        // }
        if (isset($orderData['source']) && ($orderData['source'] != 1 && $orderData['source'] != 6)) {
            return $this->returnMsg(4, '该类型不在抖音的回传中');
        }

        $this->log->info('抖音审核或发货操作结果:' . jsonEncodeMsg($orderData));
        if (empty($orderData['dist_id'])) {
            return $this->returnMsg(6, '该订单无法发货');
        }

        $douyinRModel = new DouYinRepository();
        $whereDouYin = [
            'id' => $orderData['dist_id'],
        ];
        $resDouYin = $douyinRModel->getOne($whereDouYin);
        if (empty($resDouYin)) {
            return $this->returnMsg(104, '未查询抖音配置');
        }
        //is_z_back
        if ((empty($orderData['nums']) || ($orderData['nums'] > 1) && empty($resDouYin->is_z_back))) {
            return $this->returnMsg(200, '转单不需要回传信息');
        }
        if ($isArt) {
            if (isset($resDouYin->is_z_back) && $resDouYin->is_z_back == 0) {
                return $this->returnMsg(200, '该店铺不需要回传信息');  // 暂时不需要设置 乔乔有设置
            }
        }

        // 查询抖音的数据
        $douyinModel = new DouYin($resDouYin->app_shop_id, $resDouYin->app_key, $resDouYin->app_secret);
        // $douyinModel = {};
        if (!empty($data['pid'])) {
        }
        $douyinOrder = DB::table('douyin_catch')->where(['dist_orderno' => $orderData['dist_orderno']])->first();
        if (!empty($douyinOrder->is_delive) && $douyinOrder->is_delive == 2) {
            return $this->returnMsg(200, '已发货');
        }
        if (empty($orderData['express_number'])) {
            $this->log->info('物流参数为空' . jsonEncodeMsg($orderData));
            if (empty($orderData['express_company'])) {
                return $this->returnMsg(103, '物流信息为空');
            }
            if ($orderData['express_company'] != '无需物流' && $orderData['express_company'] != '营业厅上门开卡') {
                return $this->returnMsg(103, '物流信息为空');
            }
        }
        if (empty($resDouYin->is_back) || $resDouYin->is_back != 2) {
            // 抖音审核
            $isDouYinStatus = 11;
            $isDouYinStatusDesc = '审核成功';
            $datas = [
                'status' => 0,
                'orderno' => $orderData['dist_orderno'],
            ];

            if ($isFail) {
                if (empty($orderData['created_at'])) {
                    return $this->returnMsg(101, '订单退款失败');
                }
                // var_dump(strtotime($orderData['created_at']), 1111111);
                // var_dump(time(), 22222222);
                // var_dump(46 * 60 * 60, 33333333);
                if ((time() - strtotime($orderData['created_at'])) < (46 * 60 * 60)) {
                    return $this->returnMsg(102, '请联系管理员,订单退款有问题');
                }
                // $this->log->info('抖音退款单' . json_encode($datas));
                // return $this->returnMsg(102, '请联系管理员,暂时无退款');
                $datas['status'] = 200005;
                $isDouYinStatus = 12;
                $isDouYinStatusDesc = '审核失败';
                // 判断是否是发货状态 发送失败的时候 判断下是否已经发货的状态了
                if (!empty($orderData['status']) && $orderData['status'] >= 20 && $orderData['status'] <= 40) {
                    $isDouYinStatus = 11;
                    $isDouYinStatusDesc = '审核成功';
                    $datas['status'] = 0;
                    $isFail = false;
                }
            }
            // var_dump($datas);
            // die();
            $result = $douyinModel->orderReview($datas);
            if (!empty($result)) {
                $result = json_decode($result, true);
            }
            if (empty($result['code']) || ($result['code'] != 10000)) {
                return $result;
            }
            if (!empty($result['code']) && $result['code'] == 10000) {
                DB::table('douyin_catch')->where(['dist_orderno' => $datas['orderno']])->update(['is_delive' => 1, 'status' => $isDouYinStatus, 'status_desc' => $isDouYinStatusDesc]);
            }
        }
        if ($isFail) {
            return $this->returnMsg(200, '无需发货');
        }
        sleep(5);
        // 抖音发货
        $res = $douyinModel->async($orderData);
        if (!empty($res)) {
            $res = json_decode($res, true);
            if (!empty($res['code']) && $res['code'] == 10000) {
                DB::table('douyin_catch')->where(['dist_orderno' => $datas['orderno']])->update(['status' => '20', 'status_desc' => '已发货', 'is_delive' => 2]);
                // DB::table('douyin_catch')->where()->update(['is_delive' => 2]);
            }
        }
        return $res;
    }

    // 发送短信消息
    // 商品信息的短信发送
    public function isSms($data = [], $isTrue = true)
    {
        if (empty($data['orderno'])) {
            $this->log->info('订单查询数据为空isSms');
            return $this->returnMsg(1, '订单查询数据为空');
        }
        if ($isTrue) {
            $where = [
                'orderno' => $data['orderno'],
            ];
            $data = $this->orderModel->getOne($where);
        }
        // 根据 goods_code 查询模板
        // 店铺 信息 添加一个 所有
        $whereSmsTmp = [
            // 'dist_id' => $data['shop_id'], // 去掉shop_id查询
            // 'goods_id' => $data['goods_id'],  // 去掉goods_id 的查询条件
            'product_id' => $data['product_id'], //  添加 goods_code的查询提交
            'order_status' => $data['status'],
            'status' => 0
        ];
        // var_dump($whereSmsTmp, 4444444444);
        $smsConfModel = new SmsConfRepository();
        // var_dump($whereSmsTmp);
        $resConfDatas = $smsConfModel->getAll($whereSmsTmp);
        // var_dump($resConfDatas, 4444444);
        // die();
        if (empty($resConfDatas)) {
            $this->log->info('未查询配置模板' . json_encode($data));
            return $this->returnMsg(200, '未查询配置模板');
        }
        //查询主店铺是否要发送  自己店铺里面不配置短信 查询最上面的店铺查询是否发送短信
        $resConfData = [];
        if (!empty($resConfDatas)) {
            foreach ($resConfDatas as $key => $v) {
                if (!empty($data['shop_id_str'])) {
                    $resConfArr = explode('.', $data['shop_id_str']);
                    if ($v->dist_id == $v->shop_id && in_array($v->dist_id, $resConfArr)) {
                        // 代理配置的所有分销商和自己都会发送 自己店铺
                        $resConfData = $v;
                        break;
                    } else if (in_array($v->dist_id, $resConfArr)) {
                        $resConfData = $v;
                        break;
                    }
                }
                if (empty($data['shop_id_str'])) {
                    if ($v->dist_id == $v->shop_id && $v->dist_id == $data['shop_id']) {
                        // 代理配置的所有分销商和自己都会发送 自己店铺
                        $resConfData = $v;
                        break;
                    }
                }
            }
        }
        if (empty($resConfData)) {
            $this->log->info('未查询配置模板2' . json_encode($data));
            return $this->returnMsg(200, '未查询配置模板2');
        }
        $resConfData = json_decode(json_encode($resConfData), true);
//        return $this->returnMsg(20, '未查询xx2', $resConfData);
        if (!empty($resConfData['delay'])) {
            $time = $resConfData['delay'] * 60 * 60;
            // var_dump($times);
            $resDataDelay = [
                'data' => $data,
                'confData' => $resConfData
            ];
            dispatch(new OrderSubmit($resDataDelay, 'sendSms', $time))->onQueue('TaskOrderSubmitDispose');
            return $this->returnMsg(200, '延迟发送');
        }
        // 判断是否发送过已经发送过信息
        return $this->isSmsAndSend($data, $resConfData);
    }

    // 产品类的信息短信发送
    public function isSmsProduct($data = [], $isTrue = true)
    {
        if (empty($data['ordersno'])) {
            return $this->returnMsg(1, '订单查询数据为空');
        }
        if ($isTrue) {
            $where = [
                'ordersno' => $data['ordersno'],
            ];
            $data = $this->orderModel->getOne($where);
        }
        // 根据商品查询发送模板
        $where = [
            'two_product_code' => $data['product_code'],   // 转单前的产品
            'product_code' => !empty($data['sup_product_code']) ? $data['sup_product_code'] : $data['one_product_code'],   // 转单后的产品
            'ys_product_code' => $data['one_product_code'],   // 初始产品
        ];
        $resTmp = $this->smsZModle->getAll($where);
        // 这个店铺是否可发送
        if (!$resTmp) {
            return $this->returnMsg(100, '转单未查询到配置模板');
        }
        $shopArr = [];
        if (!empty($data['shop_id_str'])) {
            $shopArr = explode(',', $data['shop_id_str']);
        }
        $resConfData = 0;
        $benSmsTmpConfigId = 0;
        foreach ($resTmp as $key => $v) {
            if ($data['shop_id'] == $v['shop_id']) {
                $benSmsTmpConfigId = $v;
                break;
            }
            if (empty($v['order_status']) || empty($data['order_status'])) {
                continue;
            }
            if (!empty($v['order_status']) && !empty($data['order_status'])) {
                $orderArr = explode(',', $v['order_status']);
                if (!in_array($data['order_status'], $orderArr)) {
                    continue;
                }
            }
            // 黑名单 验证是否是在销售或者黑名单里面
            if (!empty($v['sale_black']) && !empty($data['sell_name'])) {
                $resSaleBlack = explode(',', $v['sale_black']);
                if (in_array($data['sell_name'], $resSaleBlack)) {
                    continue;
                }
            }
            // 代理黑名单
            if (!empty($v['dist_black']) && !empty($data['shop_id'])) {
                $resDisBlack = explode(',', $v['dist_black']);
                if (in_array($data['shop_id'], $resDisBlack)) {
                    continue;
                }
            }
            if (!empty($shopArr)) {
                // 验证是否是代理的
                foreach ($shopArr as $k => $vs) {
                    if ($vs == $v['shop_id']) {
                        $resConfData = $v;
                    }
                }
            }
        }
        if (empty($smsTmpConfId) && empty($benSmsTmpConfigId)) {
            return $this->returnMsg(103, '未设置转发短信模板');
        }
        if (!empty($benSmsTmpConfigId)) {
            $resConfData = $benSmsTmpConfigId; // 自己店铺 短信优先
        }
        $resConfData = json_decode(json_encode($resConfData), true);
        if (!empty($resConfData['delay'])) {
            $time = $resConfData['delay'] * 60;
            // var_dump($times);
            $resDataDelay = [
                'data' => $data,
                'confData' => $resConfData
            ];
            // 延时短信发送
            dispatch(new OrderSubmit($resDataDelay, 'sendSms', $time))->onQueue('TaskOrderSubmitDispose');
            return $this->returnMsg(200, '延迟发送');
        }
        // 判断是否发送过已经发送过信息
        return $this->isSmsAndSend($data, $resConfData, true);
    }

    /**
     * 判断是否发过短信 + 发送短信
     *
     * @param array $data 订单数据
     * @param array $smsTmp 短信模板数据
     * @return array
     */
    public function isSmsAndSend($data = [], $smsTmp = [], $isZ = false)
    {
        // var_dump($smsTmp);
        if (empty($smsTmp['order_status']) || empty($data['status'])) {
            $this->log->info('订单状态为空' . json_encode($data));
            return $this->returnMsg(103, '订单状态为空');
        }
        if (!empty($smsTmp['order_status']) && !empty($data['status'])) {
            $orderArr = explode(',', $smsTmp['order_status']);
            if (!in_array($data['status'], $orderArr)) {
                $this->log->info('订单状态已更新不用发送' . json_encode($data));
                return $this->returnMsg(103, '订单状态已更新不用发送');
            }
        }
        // 判断是否发送过已经发送过信息
//        一个用户一个模板短信只能发送一条
        $whereLog = [
            'sms_tmp_id' => $smsTmp['sms_tmp_id'],
//            'order_status' => $data['status'],
            'order_id' => $data['id'],
            'is_send' => 2,
        ];
        $logModel = new SmsSendLogRepository();
        $resLog = $logModel->getOne($whereLog, ['id', 'status']);
        if ($resLog) {
            $this->log->info('曾经已发送,无需再次发送:' . json_encode($resLog));
            return $this->returnMsg(200, '曾经已发送,无需再次发送');
        }
        $isCharge = true;
        if (isset($resLog->status) && $resLog->status != 0) {
            $isCharge = false;
        }
        $whereTmp = [
            'id' => $smsTmp['sms_tmp_id'],
            'verify_status' => 2
        ];
        $tmpModel = new SmsTmpRepository();
        $tmpData = $tmpModel->getOne($whereTmp);
        if (empty($tmpData)) {
            $this->log->info('未查询到有效短信模板内容:' . json_encode($whereTmp));
            return $this->returnMsg(2, '未查询到模板');
        }
        if (!empty($tmpData)) {
            $tmpData = json_decode(json_encode($tmpData), true);
        }
        $tmpData['phone'] = (empty($smsTmp['is_phone']) || ($smsTmp['is_phone'] == 1)) ? $data['pay_phone'] : $data['iccid'];
        // 短信内容替换
        $smsTmp['is_send'] = 1;
        $smsTmp['status'] = 1;
        $smsTmp['phone'] = $tmpData['phone'];
        $SmsApi = new SmsClient();
        $tplParamsData = $data;
        $smsTmp['content'] = $SmsApi->parseTplContent($tmpData['content'], $tplParamsData);
        $smsTmp['order_id'] = $data['id'];
        if ($isZ) {
            $smsTmp['remark'] = '原始套餐:' . $data['one_product_name'] . '上游套餐:' . $data['sup_product_name'];
        }
        if ($isCharge) {
            $resDe = $this->deductExpen($data, $data['shop_id'], 3);
            $smsTmp['reason'] = !empty($resDe['msg']) ? $resDe['msg'] : '';
            if (empty($resDe['code']) || $resDe['code'] != 200) {
                $this->log->info('短信扣费失败:' . json_encode($resDe));
                return $this->returnMsg(2, '短信扣费失败');
            }
        }
        if (!empty($data['sell_name'])) {
            $isAgren = DB::table('sms_agent')->where(['name' => $data['sell_name']])->first();
            if (!empty($isAgren)) {
                return $this->returnMsg(2, '该订单存在于分销商黑名单中');
            }
        }
        // 短信发送是否开启
        $resIsSms = DB::table('system')->where(['name' => 'is_sms'])->first();
        if (empty($resIsSms) || empty($resIsSms->val)) {
            return $this->returnMsg(2, '短信发送未开启');
        }
        // 短信日志状态为等待回执
        $smsTmp['status'] = 3;
        $smsTmp['sms_id'] = 'waitsendback';
        if (empty($tmpData['tpl_id'])) {
            $smsTmp['remark'] = '缺少短信模板';
        }
        $res = $logModel->add($smsTmp);
        if ($res['code'] != 200 || empty($res['data']['id'])) {
            $this->log->info('短信发送日志保存失败' . json_encode($smsTmp) . '返回结果:' . json_encode($res));
            return $res;
        }
//        现在只能使用短信模板发送,所以没有模板的不用再执行下去了
        if (empty($tmpData['tpl_id'])) {
            $this->log->info('短信模板没找到:' . json_encode($tmpData));
            return $this->returnMsg(2, '短信模板没找到');
        }
        $logId = $res['data']['id'] ?? 0;
//        return $this->returnMsg(12, '订单状态已更新不用发送', $tmpData);
//        开始发短信
        $res = $this->pushSmsCline($tmpData, $tplParamsData);
        if ($res['code'] != 200) {
            $this->log->info('短信发送失败' . json_encode($tmpData) . ';参数:' . json_encode($tplParamsData) . '返回结果:' . json_encode($res));
//            修改日志为没发送与失败
            $logModel->edit(['id' => $logId], [
                'status' => 1,
                'is_send' => 1,
                'remark' => $res['msg'] ?? ''
            ]);
            return $res;
        }
        // 短信日志状态为等待回执
        $logModel->edit(['id' => $logId], [
            'status' => 2,
            'is_send' => 2,
            'sms_id' => $res['data']['smsId']
        ]);

        return $this->returnMsg(200, '短信发送完成');
    }

    //发送短信方法
    public function pushSmsCline($data, $tplParamsData = [])
    {
        $tplId = $data['tpl_id'] ?? '';
        $phone = $data['phone'] ?? '';
        if (empty($tplParamsData) && isset($data['param']) && is_array($data['param'])) {
            $tplParamsData = $data['param'];
        }
        $model = new SmsClient(3);
        if (empty($tplId)) {
            $data['content'] = $model->parseTplContent($data['content'], $tplParamsData);
            $res = $model->sendSms($phone, $data['content'], $data['type']);
        } else {
            $res = $model->sendSmsByTpl($phone, $tplId, $data['type'], $data['content'], $tplParamsData);
        }
        return $res;
    }

    //短信回复的方法
    public function replySms($where)
    {
        $model = new SmsReplyRepository();
        $wheres = [
            'id' => $where['ordersno']
        ];
        $data = $model->getOne($wheres);
        if (!$data) {
            return false;
        }
        $content = '';
        if (!empty($data->reply_content)) {
            $res = explode('回复:', $data->reply_content);
            $content = $res;
            if (is_array($res)) {
                $content = end($res);
            }
        }
        $content = str_replace('<br/>', '', $content);
        $logModel = new SmsSendLogRepository();
        $resConfData = [
            'phone' => $data->phone,
            'content' => $content,
            'sms_tmp_id' => '1',
            'order_status' => '1'
        ];
        $tmpData = [
            'phone' => $data->phone,
            'content' => $content,
            'name' => '开心连连'
        ];
        $res = $this->pushSmsCline($tmpData);
        if (!empty($res['code']) && $res['code'] == 200) {
            // 扣费
            $resConfData['status'] = 0;
        }
        $resConfData['reason'] = !empty($res['msg']) ? $res['msg'] : '';
        $ress = $logModel->add($resConfData);
        return $ress;
    }

    // 短信提醒信息
    public function warnSms($where)
    {
//        $model = new SmsClient();
//        $res = $model->getBalance();
//        $balance = 0;
//        if (!empty($res['data']) && $res['code'] == 200) {
//            $balance = $res['data']['balance'];
//        }
//        if ($balance <= 100) {
//            $content = '短信余额:' . $balance . '元,请及时充值';
//            $phone = '15225070393';
//            $tmpData = [
//                'tpl_id' => '520416',
//                'phone' => $phone,
//                'param' => ["money" => $balance],
//                'content' => $content
//            ];
//            $res = $this->pushSmsCline($tmpData);
//        }
//        // $time = 24 * 60 * 60;
//        // 现在到对应时间的秒
//        $date = time();
//        $SetTime = strtotime(date('Y-m-d 09:00:00', strtotime('+1 days')));
//        $time = $SetTime - $date;
//        dispatch(new OrderSubmit(1, 'smsWarn', $time))->onQueue('TaskOrderSubmitDispose');
//        return $res;
    }
    // 推送消息

    /**
     * 感叹号推送信息
     */
    public function pushGanMessage($data = [], $isTrue = true)
    {
        if (empty($data['orderno'])) {
            return $this->returnMsg(1, '未查询到订单数据');
        }
        if ($isTrue) {
            $where = [
                'orderno' => $data['orderno'],
            ];
            $data = $this->orderModel->getOne($where);
        }
        // $returnRes = [
        //     'orderno' => $data['orderno'],
        //     'iccid' => $data['iccid'],
        //     'express_company' => $data['express_company'],
        //     'express_number' => $data['express_number'],
        //     'order' => $data['dist_orderno'],
        //     'first_amount' => $data['first_status_desc'],
        //     'status' => $data['status'],
        //     'msg' => $data['three_msg']
        // ];
        $status = 1;
        switch ($data['status']) {
            case 1:
                $status = 1;
                break;
            case 10:
                $status = 1;
                break;
            case 20:
                $status = 4;
                break;
            case 30:
                $status = 5;
                break;
            case 40:
                $status = 6;
                break;
            case 50:
                $status = 13;
                break;
            case 51:
                $status = 13;
                break;
            case 60:
                $status = 13;
                break;
        }
        // 邮政EMS
        // 京广速递
        // 京东配送
        // 顺丰快递

        if (!empty($data['express_company']) && $data['express_company'] == 'EMS') {
            $data['express_company'] = '邮政EMS';
        } else if (!empty($data['express_company']) && strstr($data['express_company'], '顺丰')) {
            $data['express_company'] = '顺丰快递';
        } elseif (!empty($data['express_company']) && strstr($data['express_company'], '京东')) {
            $data['express_company'] = '京东配送';
        } elseif (!empty($data['express_company']) && strstr($data['express_company'], '邮政')) {
            $data['express_company'] = '邮政EMS';
        } elseif (!empty($data['express_company']) && strstr($data['express_company'], '京广')) {
            $data['express_company'] = '京广速递';
        }
        $returnRes = [
            'iccid' => $data['iccid'],
            'order_num' => $data['dist_orderno'],
            'orderno' => $data['dist_orderno'],
            'order' => $data['orderno'],
            'express_company' => $data['express_company'],
            'express_number' => $data['express_number'],
            'status' => $status,
            'three_msg' => $data['three_msg'] . '上游' . $data['card_status_desc'],
            'msg' => $data['three_msg'] . '上游' . $data['card_status_desc']
        ];
        // $userModel = new AdminUsersRepository();
        // $res = $userModel->getOne(['id' => $data['shop_id']], ['push_url']);
        $url = 'http://notify.91haoka.cn/api/plan-market/order/yuxuan-henanchenqi/notify';
        // $url = 'https://91haoka.cn/api/plan-market/order/yuxuan/notify';
        $isGetUrl = DB::Table('system')->where(['name' => 'gantanhao_return'])->first();
        if (!empty($isGetUrl) && !empty($isGetUrl->val)) {
            $url = $isGetUrl->val;;
        }
        if ($url == 1) {
            return $this->returnMsg(200, '不用推送');
        }
        // $url = 'http://notify.91haoka.cn/api/plan-market/upstreamOrder/qiaoqiao-jiusan-common/order/notify';
        if (!empty($url)) {
            // $url = 'http://adminnew.chenqiwangluo.com/api/v1/catchOrder';
            // $url = 'https://666.dx10000.com/unicom/call_back/YuXuanCallBack'; //诺宇
            $url = $url;
            $resSS = $this->pushMessageCline($returnRes, $url, false);
            // var_dump($resSS);
        }
        return $this->returnMsg(200, '查询成功', !empty($resSS) ? $resSS : []);
    }

    /**
     * 推送信息
     *
     * @param array $data // 订单数据或查询数据
     * @param boolean $isTrue 是否需要查询订单
     * @return void
     */
    public function pushMessage($data = [], $isTrue = true)
    {
        if (empty($data['orderno'])) {
            return $this->returnMsg(1, '未查询到订单数据');
        }
        if ($isTrue) {
            $where = [
                'orderno' => $data['orderno'],
            ];
            $data = $this->orderModel->getOne($where);
        }
        $returnRes = [
            'orderno' => $data['orderno'],
            'iccid' => $data['iccid'],
            'express_company' => $data['express_company'],
            'express_number' => $data['express_number'],
            'order' => $data['dist_orderno'],
            'first_amount' => $data['first_status_desc'],
            'status' => $data['status'],
            'msg' => $data['three_msg'] . '上游' . $data['card_status_desc']
        ];
        $userModel = new AdminUsersRepository();
        $res = $userModel->getOne(['id' => $data['shop_id']], ['push_url']);
        if (!empty($res->push_url)) {
            // $url = 'http://adminnew.chenqiwangluo.com/api/v1/catchOrder';
            // $url = 'https://666.dx10000.com/unicom/call_back/YuXuanCallBack'; //诺宇
            $url = $res->push_url;
            $resSS = $this->pushMessageCline($returnRes, $url);
            // var_dump($resSS);
        }
        return $this->returnMsg(200, '查询成功', !empty($resSS) ? $resSS : []);
    }

    // 推送消息 方法
    public function pushMessageCline($data, $url, $isTrue = true)
    {
        $pathPrem = public_path('prems/cacert.pem');
        $client = new Client(['verify' => $pathPrem]);
        if ($isTrue) {
            $requests = function () use ($data, $url) {
                yield new req('POST', $url, ['X-Foo' => 'bar'], json_encode($data));
            };
        }
        if (!$isTrue) {
            $requests = function () use ($data, $url) {
                yield new req('POST', $url, ['X-Foo' => 'bar', 'Content-Type' => 'application/json'], json_encode($data));
            };
        }
        $line = 1;
        $pool = new Pool($client, $requests(), [
            'concurrency' => $line,
            'fulfilled' => function ($response, $index) use ($data, $url) {
                // var_dump($response, 111111111);
                // var_dump($index, 2222222);
                //忽略响应只获取下游url是否可以发送；
                //$code = $response->getStatusCode(); // 200
                //$reason = $response->getReasonPhrase(); // OK
                //发送成功且回复为1则仍进成功数据，等待删除，其他仍入失败
                $body = $response->getBody()->getContents();
                // var_dump($body, 11111111111);
                if (!empty($body)) {
                    $res = json_decode($body, true);
                    $this->log->info('推送信息返回的地址' . $url . '参数' . jsonEncodeMsg($data) . '结果' . jsonEncodeMsg($res));
                    if (!empty($res['code']) && $res['code'] != 0) {
                        // $time = 60 *1;
                        // dispatch(new OrderSubmit($data, 'pushOrder'))->onQueue('TaskOrderSubmitDispose')->delay(Carbon::now()->addMinutes($time));
                    }
                }
                // $this->root->info('推送结果返回值:' . $body);
                // $body == 1 ? $this->_success  = 2 : $this->_success = 1;
            },
            'rejected' => function ($reason, $index) {
                $this->log->info('推送失败信息返回的参数' . jsonEncodeMsg($reason));
                //忽略错误提示
                // var_dump($reason, 1111111111);
                // var_dump($index, 333333333);
            },
        ]);
        $this->log->info('推送参数' . $url . '参数:' . jsonEncodeMsg($data));
        $promise = $pool->promise();
        $promise->wait();
        return 1;
    }

    // 验证信息 失败 如何处理 这个地方可以添加验证
    // 到提交到第三方的也可以 提交验证
    //产品效验
    public function validProduct($productId, $data)
    {
        if (empty($productId)) {
            return $this->returnMsg(3, '产品信息不能为空');
        }
        $resProduct = $this->productModel->getOne(['id' => $productId]);
        if (!$resProduct) {
            return $this->returnMsg(4, '未查询到产品信息');
        }
        // 产品所有的信息 验证
        // var_dump($resProduct, 2222222222);
        // 是否需要身份证号信息
        if (isset($resProduct->is_identity) && $resProduct->is_identity == 0) {
            if (empty($data['identity'])) {
                return $this->returnMsg(10007, '身份证号码位数不正确，请检查');
            }
            if (!is_idcard($data['identity'])) {
                return $this->returnMsg(10007, '身份证号码不正确，请检查');
            }
        }
        // 年龄限制
        if (!empty($data['identity'])) {
            $age = getAgeByID($data['identity']);
            if (!empty($resProduct->limit_max_age) && !empty($resProduct->limit_min_age)) {
                if ($age > $resProduct->limit_max_age || $age < $resProduct->limit_min_age) {
                    return $this->returnMsg(5, "很抱歉，用户年龄需要在{$resProduct->limit_min_age}～{$resProduct->limit_max_age}才可下单");
                }
            }
        }


        //开卡限制
        //单人开卡数量限制
        if (!empty($resProduct->max_number)) {
            $where = [];
            if (!empty($resProduct->cycle)) {
                $time = date('Y-m-d 00:00:00', strtotime("-$resProduct->cycle month"));
                $where[] = ['created_at', '>=', $time];
            }
            if (!empty($data['identity'])) {
                $where[] = ['idcard', '=', $data['identity']];
            }
            $where[] = ['phone', '=', $data['contact']];
            $where[] = ['shop_id', '=', $data['shop_id']];
            $where[] = ['product_id', '=', $resProduct->id];
            $count = $this->orderProductModel->getCount($where);
            if ($resProduct->max_number <= $count) {
                return $this->returnMsg(10000, '开卡数量超过限制');
            }
        }
        // 用户的禁发地 和只发地设置
        // 禁发地
        $isProh = true;
        if (!empty($resProduct->prohibit)) {
            $resProh = explode(',', $resProduct->prohibit);
            // 省市区 的限制
            $province = str_replace('省', '', $data['province']);
            $province = str_replace('市', '', $province);
            $citys = str_replace('市', '', $data['city']);
            $areas = str_replace('区', '', $data['area']);
            if (in_array($data['province'], $resProh)) {
                $msgPro = '该省份在禁止发货';
                $isProh = false;
            }
            if ($isProh && in_array($data['city'], $resProh)) {
                $msgPro = '该市禁止发货';
                $isProh = false;
            }
            if ($isProh && in_array($data['area'], $resProh)) {
                $msgPro = '该区禁止发货';
                $isProh = false;
            }
            if ($isProh && in_array($province, $resProh)) {
                $msgPro = '该省份在禁止发货';
                $isProh = false;
            }
            if ($isProh && in_array($citys, $resProh)) {
                $msgPro = '该市禁止发货';
                $isProh = false;
            }
            if ($isProh && in_array($areas, $resProh)) {
                $msgPro = '该区禁止发货';
                $isProh = false;
            }
        }
        if ($isProh && !empty($resProduct->onlyregion)) {
            $resProh = explode(',', $resProduct->onlyregion);
            // 省市区 的限制
            $province = str_replace('省', '', $data['province']);
            $province = str_replace('市', '', $province);
            $citys = str_replace('市', '', $data['city']);
            $areas = str_replace('区', '', $data['area']);
            $isOnly = 0;
            if (!in_array($data['province'], $resProh)) {
                $msgPro = '该省份在禁止发货';
                $isProh = false;
                $isOnly++;
            }
            if ($isProh && !in_array($data['city'], $resProh)) {
                $msgPro = '该市禁止发货';
                $isProh = false;
                $isOnly++;
            }
            if ($isProh && !in_array($data['area'], $resProh)) {
                $msgPro = '该区禁止发货';
                $isProh = false;
                $isOnly++;
            }
            if ($isProh && !in_array($province, $resProh)) {
                $msgPro = '该省份在禁止发货';
                $isProh = false;
                $isOnly++;
            }
            if ($isProh && !in_array($citys, $resProh)) {
                $msgPro = '该市禁止发货';
                $isProh = false;
                $isOnly++;
            }
            if ($isProh && !in_array($areas, $resProh)) {
                $msgPro = '该区禁止发货';
                $isProh = false;
                $isOnly++;
            }
            if ($isOnly < 6) {
                $isProh = true;
            }
        }
        if (!$isProh) {
            return $this->returnMsg(1006, !empty($msgPro) ? $msgPro : '禁发');
        }
        return $this->returnMsg(200, '验证成功');
        // 提交到第三方
        $channelData = [
            'product_code' => $resProduct->product_code,
            'product_id' => $resProduct->id,
            'is_charm' => $resProduct->is_charm,
            'shop_id' => $resProduct->shop_id,
        ];
        $resChannel = $this->moreChannel($channelData, $data);
        return $resChannel;
    }

    /**
     * 多渠道查询
     * 同一个商品提交到不同的 渠道
     * @param [type] $jsonData
     * @param [type] $data
     * @return void
     */
    public function moreChannel($jsonData, $data, $isTrue = false)
    {
        // var_dump($data);
        $productCode = $jsonData['product_code'];
        if (!empty($jsonData['product_code']) && $jsonData['product_code'] == 1) {
            $productCode = $jsonData['goods_code'];
        }
        $where = [
            'shop_id' => $jsonData['shop_id'],
            'product_code' => $productCode,
            'status' => 0
        ];
        if ($isTrue) {
            if (!empty($data['sup_id'])) {
                $where = [
                    'channel_id' => $data['sup_id'],
                    'shop_id' => $jsonData['shop_id'],
                    'product_code' => $productCode,
                ];
                // return $this->returnMsg(100, '未设置当前通道');
            }
        }
        // status = 0 可以提交 status=1 不能提交
        // var_dump($where);
        // $this->log->info('查询通道的参数:' . json_encode($where));
        $resChannel = $this->channelModel->getAllProduct($where);
        // 防止不要脸的循环
        if (!empty($data['channel_error_josn']) && !$isTrue) {
            if (count(json_decode(json_encode($resChannel), true)) <= (count(json_decode($data['channel_error_josn']), true) + 1)) {
                // 应该调用商品转单的
                return $this->returnMsg(20000, '提交的到头了 不用在提交了');
            }
        }
        // if (empty(json_decode(json_encode($resChannel), true))) {
        // var_dump($resChannel, 222222222);
        $this->log->info('参数结果:' . jsonEncodeMsg($resChannel));
        if (empty($resChannel)) {
            $isTrueChannel = true;
            if (!empty($data['sup_id'])) {
                $isTrueChannel = false;
                $wheres = [
                    'shop_id' => $jsonData['shop_id'],
                    'product_code' => $productCode,
                    'status' => 0
                ];
                $resChannel = $this->channelModel->getAllProduct($wheres);
                if (!empty($data['channel_error_josn']) && !$isTrue) {
                    if (count(json_decode(json_encode($resChannel), true)) <= (count(json_decode($data['channel_error_josn']), true) + 1)) {
                        // 应该调用商品转单的
                        return $this->returnMsg(20000, '提交的到头了 不用在提交了');
                    }
                }
            }
            if (empty($resChannel)) {
                if ($isTrueChannel) {
                    return $this->returnMsg(10000, '未查询到关联的通道');
                }
                return $this->returnMsg(10000, '重新提交中未查询到上游通道');
            }
        }
        $returnMsg = [];
        $jsonReturn = [];
        $flag = false;
        $chinnelId = '';
        $chinnelName = '';
        foreach ($resChannel as $key => $v) {
            $chinnelId = $v['channel_id'];
            $this->log->info('渠道名称记录' . $chinnelId);
            $chinnelName = $v['channel_name'];
            $this->log->info('渠道名称记录' . $chinnelName);
            // 判断是否已经提交过了
            if (!empty($data['channel_error_josn']) && $data['channel_error_josn'] != '[]' && !$isTrue) {
                $errorJson = json_decode($data['channel_error_josn'], true);
                $jsonReturn = $errorJson;
                if (!empty($jsonReturn)) {
                    $array_error = [];
                    foreach ($errorJson as $keys => $vals) {
                        $array_error[] = $vals['channel_id'];
                    }
                    if (in_array($v['channel_id'], $array_error)) {
                        // 防止重复提交的条件确认  1: 自己点击提交 2:物流返回提交的
                        // echo 44444444;
                        $this->log->info('隔过去的渠道参数' . jsonEncodeMsg($v));
                        continue;
                    }
                }
            }
            $data['model'] = $v['channel_id'];
            $data['channel_code'] = $v['channel_code'];
            $datas = $this->getWay($data);
            $data = array_merge($data, $datas);
            // if (empty($data['channel_id'])) {
            //     $data['channel_id'] = $v['channel_id'];
            // }
            if (empty($jsonData['is_charm'])) {
                $resCheck = $this->orderSubmitThree('checkOrder', $data);
                if (empty($resCheck['code']) || $resCheck['code'] != 200) {
                    $returnMsg = $resCheck;
                    $jsonReturn[] = [
                        'channel_id' => $v['channel_id'],
                        'channel_name' => $v['channel_name'],
                        'msg' => !empty($resCheck['msg']) ? $resCheck['msg'] : '未知错误'
                    ];
                    // 判断是否是异常单
                    if (!$this->isAbn($returnMsg['msg'], $data['anb'])) {
                        $flag = true;
                        continue;
                    }
                    continue;
                }
            }
            $returnMsg = $this->orderSubmitThree('orderSubmit', $data);
            // var_dump($returnMsg);
            $this->log->info('多通道测试代理的提交信息参数' . jsonEncodeMsg($data) . '结果' . jsonEncodeMsg($returnMsg));
            if (empty($returnMsg['code']) || $returnMsg['code'] != 200) {
                // $returnMsg = $resSubmit;
                $jsonReturn[] = [
                    'channel_id' => $v['channel_id'],
                    'channel_name' => $v['channel_name'],
                    'msg' => !empty($returnMsg['msg']) ? $returnMsg['msg'] : '未知错误',
                ];
                // 判断是否是异常单
                if (!$this->isAbn($returnMsg['msg'], $data['anb'])) {
                    $flag = true;
                    continue;
                }
                continue;
            }

            break;
        }
        if (empty($returnMsg['code']) || $returnMsg['code'] != 200) {
            $jsonReturns = array_pop($jsonReturn);
        }
        $returnMsg['data']['channel_id'] = $chinnelId;
        $returnMsg['data']['channel_name'] = $chinnelName;
        $returnMsg['data']['error'] = json_encode($jsonReturn);
        $returnMsg['data']['is_anb'] = $flag;
        $this->log->info('多渠道参数返回数据' . jsonEncodeMsg($returnMsg));
        return $returnMsg;
    }

    //第三方的统一调用
    public function orderSubmitThree($method, $data)
    {
        $model = new Transfer();
        return $model->$method($data);
    }

    // 查询通道参数
    public function getWay($data)
    {
        // 查询单个通道
        $model = new WayRepository();
        $resChannelModel = $model->getOne(['id' => $data['model']]);
        $this->log->info('查询通道出来的参数A:' . jsonEncodeMsg($resChannelModel));
        if (!$resChannelModel) {
            return $this->returnMsg(102, '通道不存在');
        }
        $data['path'] = $resChannelModel->path;
        $data['url'] = $resChannelModel->url;
        $data['parame'] = $resChannelModel->parame;
        $data['anb'] = $resChannelModel->anb;
        return $data;
    }

    // 扣除费用
    public function deductExpen($data = array(), $shop_str = '', $type = 1)
    {
        //$this->userMoneyLog->store();
//        $this->log->info('数1据订单后续bug19' . jsonEncodeMsg($data) . '数据:' . ($shop_str));
        $array = [];
        if (empty($shop_str)) {
            $array = [$data['shop_id']];
        }
        if (!empty($shop_str)) {
            $array = explode('.', $shop_str);
        }

        $data = [
            'ordernum' => $data['orderno'], //
            'money' => '',
            'shop_id' => '',
            'type' => $type,
        ];
        $where = [];
        if ($type == 1) {
            $where = [
                'dict_type' => 'sys_frees_stand_order',
            ];
        } else if ($type == 2) {
            $where = [
                'dict_type' => 'sys_frees_stand_status',
            ];
        } else if ($type == 3) {
            $where = [
                'dict_type' => 'sys_snd_sms'
            ];
        }
        if (empty($where)) {
            return $this->returnMsg(104, '收费类型不正确');
        }
        $model = new DictDatarRepository();
        $moneyArr = $model->getOne($where);
        // $this->log->info('数1据订单后续bug20' . json_encode($data) . '数据:' . json_encode($moneyArr));
        if (!($moneyArr)) {
            return $this->returnMsg(105, '未查询到收费类型');
        }
        if (empty($moneyArr->dict_value)) {
            // $this->log->info('数1据订单后续bug21' . json_encode($data) . '数据:' . json_encode($moneyArr));
            return $this->returnMsg(200, '该项目不收费');
        }
        $data['money'] = -$moneyArr->dict_value;
        $res = [];
        foreach ($array as $key => $v) {
            if (empty($v)) {
                continue;
            }
            $data['shop_id'] = $v;
            $res = $this->userMoneyLog->store($data);
            if (empty($res['code']) || $res['code'] != 200) {
                $res['data']['is_all'] = '代理欠费';
                break;
            }
        }
        return $res;
    }

    // 判断是否是异常单
    public function isAbn($msg = '', $data = '')
    {
        if (!empty($data) && is_string($data)) {
            $data = explode(',', $data);
        }
        if (!empty($data) && !empty($msg)) {
            if (in_array($msg, $data)) {
                return true;
            }
        }
        return false;
    }

    //订单状态后续处理  第三方返回状态后的处理
    public function followOrderStatus($where = [], $data = [], $isDecrpt = [], $isChannel = false)
    {
//        var_dump($data);  //1.订单发货收费 2.是否发送短信 3. 是否推送信息  4. 失败订单处理
//        $this->log->info('数1据订单后续bug13' . json_encode($where) . '数据:' . json_encode($data));
        if (empty($where)) {
            $this->log->info('数据订单后续bug' . jsonEncodeMsg($where));
            return $this->returnMsg(1, '查询条件不能为空');
        }
        $isEditTrue = false;
        foreach ($where as $key => $v) {
            if (empty($v)) {
                $isEditTrue = true;
                break;
            }
        }
        if ($isEditTrue) {
            $this->log->info('数据订单后续bug2' . json_encode($where));
            return $this->returnMsg(1, '查询条件不能为空');
        }
        $resOrder = $this->orderModel->getOne($where);
        // var_dump($resOrder);
//        $this->log->info('数1据订单后续bug14' . json_encode($where) . '数据:' . json_encode($data) . 'data:' . json_encode($resOrder));
        // 判断是否是否需要
        if (!$resOrder) {
            // $this->log->info('数据订单后续bug2' . json_encode($where));
            return $this->returnMsg(2, '未查询到订单');
        }
        if ($resOrder['forbid_status'] == 1) {
            unset($data['status']);
        }
        if ($resOrder['forbid_activat_status'] == 1) {
            unset($data['activat_status']);
        }
        if ($resOrder['forbid_first_status'] == 1) {
            unset($data['first_status']);
        }

//        $this->log->info('数1据订单后续bug15' . json_encode($where) . '数据:' . json_encode($data));
        // 订单发货的话 需要收费
        if (!empty($data['status']) && $data['status'] >= 10) {

            if (empty($data['orderno'])) {
                $data['orderno'] = $resOrder['orderno'];
            }
            $this->log->info('数1据订单后续bug18' . jsonEncodeMsg($where) . '数据:' . jsonEncodeMsg($data));
            // $resShop_id = !empty($resOrder['shop_id_str']) ? $resOrder['shop_id_str'] : $resOrder['shop_id'];
            $resDeduct = $this->deductExpen($resOrder, $resOrder['shop_id_str'], 2);
            // $this->log->info('数1据订单后续bug16' . json_encode($where) . '数据:' . json_encode($resDeduct));
            if (empty($resDeduct['code']) || $resDeduct['code'] != 200) {
                // $this->log->info('数据订单后续bug3' . json_encode($resDeduct));
                // return $this->returnMsg(106, '扣费失败');
                $this->log->info('扣费失败的订单' . jsonEncodeMsg($resOrder) . '返回的结果:' . jsonEncodeMsg($resDeduct));
            }
        }
        // 查看字段是否需要解密
        if (!empty($isDecrpt)) {
            // $this->log->info('数据订单后续bug4' . json_encode($where));
            $data['model'] = $resOrder['sup_id'];
            $ChannelArr = $this->getWay($data);
            $datas = array_merge($ChannelArr, $isDecrpt);
            $data = $this->orderSubmitThree('decryptDES', $datas);
        }
        // $this->log->info('数1据订单后续bug17' . json_encode($where) . '数据:' . json_encode($resDeduct));
        if (empty($where['ordersno'])) {
            $where['ordersno'] = $resOrder['ordersno'];
        }
        if (!empty($data['express_number'])) {
            $str = substr($data['express_number'], 0, 2);
            if ($str == 'JD' || $str == 'jd') {
                $data['express_company'] = '京东快递';
            } else if ($str == 'SF' || $str == 'sf') {
                $data['express_company'] = '顺丰';
            }
        }
        if (!empty($data['express_number']) && !empty($data['express_company'])) {
            // 判断是否发送短信
            $modelsExpress = new MainOrderTwoRepostition();
            $editStatus = $modelsExpress->expressTrack($data['express_company'], $data['express_number']);
            $this->log->info('物流信息参数' . json_encode($where) . '返回结果:' . json_encode($editStatus));
        }
//        $this->log->info('数据订单后续bug12' . json_encode($where) . '数据:' . json_encode($data));
        return $this->editOrderThree($where, $data, $isChannel);
    }

    // 商品转单
    public function isGoodsProduct($data = [], $isTrue = true)
    {
        if (empty($data['ordersno'])) {
            return $this->returnMsg(1, '订单查询数据为空');
        }
        if ($isTrue) {
            $where = [
                'ordersno' => $data['ordersno'],
            ];
            $data = $this->orderModel->getOne($where);
        }
        // 根据商品查询发送模板
        $where = [
            'product_code' => !empty($data['sup_product_code']) ? $data['sup_product_code'] : $data['one_product_code'],   // 转单前的产品
            'ys_product_code' => $data['one_product_code'],   // 初始产品
        ];
        // var_dump($where);
        $resTmp = $this->goodsZModle->getAll($where);
        // var_dump($resTmp);
        // 这个店铺是否可发送
        if (!$resTmp) {
            return $this->returnMsg(100, '转单未查询到配置模板');
        }
        $shopArr = [];
        if (!empty($data['shop_id_str'])) {
            $shopArr = explode(',', $data['shop_id_str']);
        }
        $resConfData = 0;
        $benSmsTmpConfigId = 0;
        foreach ($resTmp as $key => $v) {
            if ($data['shop_id'] == $v['shop_id']) {
                $benSmsTmpConfigId = $v;
                break;
            }
            // 判断订单状态
            if (empty($v['order_status']) || empty($data['order_status'])) {
                continue;
            }
            if (!empty($v['order_status']) && !empty($data['order_status'])) {
                $orderArr = explode(',', $v['order_status']);
                if (!in_array($data['order_status'], $orderArr)) {
                    continue;
                }
            }
            // 黑名单 验证是否是在销售或者黑名单里面
            if (!empty($v['sale_black']) && !empty($data['sell_name'])) {
                $resSaleBlack = explode(',', $v['sale_black']);
                if (in_array($data['sell_name'], $resSaleBlack)) {
                    continue;
                }
            }

            // 代理黑名单
            if (!empty($v['dist_black']) && !empty($data['shop_id'])) {
                $resDisBlack = explode(',', $v['dist_black']);
                if (in_array($data['shop_id'], $resDisBlack)) {
                    continue;
                }
            }
            if (!empty($shopArr)) {
                // 验证是否是代理的
                foreach ($shopArr as $k => $vs) {
                    if ($vs == $v['shop_id']) {
                        $resConfData = $v;
                    }
                }
            }
        }
        if (empty($smsTmpConfId) && empty($benSmsTmpConfigId)) {
            return $this->returnMsg(103, '未设置转发订单模板');
        }
        if (!empty($benSmsTmpConfigId)) {
            $resConfData = $benSmsTmpConfigId; // 自己店铺 短信优先
        }
        $resConfData = json_decode(json_encode($resConfData), true);
        if (!empty($resConfData['delay'])) {
            $time = $resConfData['delay'] * 60;
            // var_dump($times);
            $resDataDelay = [
                'data' => $data,
                'confData' => $resConfData['two_product_code']
            ];
            // 延时转发发送
            dispatch(new OrderSubmit($resDataDelay, 'sendGoodsZ', $time))->onQueue('TaskOrderSubmitDispose');
            return $this->returnMsg(200, '延迟发送');
        }
        // 判断是否发送过已经发送过信息
        return $this->isGoodsAndSend($data, $resConfData['two_product_code'], true);
    }

    // 自动转单
    public function isGoodsAndSend($data, $product_code)
    {
        if (empty($product_code)) {
            return $this->returnMsg(102, '未传递需要转发的参数');
        }
        $whereGoods = [
            'product_code' => $product_code,
            'shop_id' => $data['shop_id'],
            'status' => 0
        ];
        // var_dump($whereGoods, 11111111);
        $resGoods = $this->goodsModel->getOne($whereGoods);
        if (!$resGoods) {
            return $this->returnMsg(103, '未查询到商品');
        }
        $update = [
            'goods_id' => $resGoods->id
        ];
        $whereEditOrders = [
            'ordersno' => $data['ordersno'],
        ];
        return $this->orderModel->edit($whereEditOrders, $update, false, true, 1);
    }

    // 拼多多 发货信息
    public function sendPddComPany($orderData, $isTrue)
    {
        // if (empty($data['dist_id'])) {
        // }
        // $model =  new Pdd('8cf316c95680426881845b559c80937004ed70d8', $ilic, $client_secret, '', $shop, 30);
        // $model->getCompany($data);
        if ($isTrue) {
            if (!empty($orderData['orderno'])) {
                $where = ['orderno' => $orderData['orderno']];
            }
            if (!empty($orderData['dist_orderno'])) {
                $where = ['dist_orderno' => $orderData['dist_orderno']];
            }
            if (!empty($orderData['ordersno'])) {
                $where = ['ordersno' => $orderData['ordersno']];
            }
            $orderData = $this->orderModel->getOne($where);
        }
        // $this->log->info('抖音审核订单处理:' . json_encode($where));
        // if ($orderData['status'] != 20) {
        //     return $this->returnMsg(3, '该状态不在提交中');
        // }
        if (isset($orderData['source']) && ($orderData['source'] != 11)) {
            return $this->returnMsg(4, '该类型不在拼多多的回传中');
        }

        $this->log->info('拼多多审核或发货操作结果:' . jsonEncodeMsg($orderData));
        if (empty($orderData['dist_id'])) {
            return $this->returnMsg(6, '该订单无法发货');
        }

        $douyinRModel = new PddRepository();
        $whereDouYin = [
            'id' => $orderData['dist_id'],
        ];
        $resDouYin = $douyinRModel->getOne($whereDouYin);
        if (empty($resDouYin)) {
            return $this->returnMsg(104, '未查询抖音配置');
        }
        //is_z_back
        if ((empty($orderData['nums']) || ($orderData['nums'] > 1) && empty($resDouYin->is_z_back))) {
            return $this->returnMsg(200, '转单不需要回传信息');
        }
        // 查询抖音的数据
        // $douyinModel = new Pdd($resDouYin->app_shop_id, $resDouYin->app_key, $resDouYin->app_secret);
        $douyinModel = new Pdd($resDouYin->params, $resDouYin->client_id, $resDouYin->client_secret, '', $resDouYin->id, 30);;
        // $douyinModel = {};
        if (!empty($data['pid'])) {
        }
        if ($orderData['status'] > 40) {
            // 失败单处理
            $resFail = $douyinModel->failOrder($orderData);
            $this->logOrder->info('拼多多失败单:' . json_encode($orderData) . '失败返回' . json_encode($orderData));
            return $resFail;
        }
        $douyinOrder = DB::table('pdd_catch')->where(['dist_orderno' => $orderData['dist_orderno']])->first();
        if (!empty($douyinOrder->is_delive) && $douyinOrder->is_delive == 2) {
            return $this->returnMsg(200, '已发货');
        }
        if (empty($orderData['express_number'])) {
            $this->log->info('物流参数为空' . jsonEncodeMsg($orderData));
            if (empty($orderData['express_company'])) {
                return $this->returnMsg(103, '物流信息为空');
            }
            if ($orderData['express_company'] != '无需物流' && $orderData['express_company'] != '营业厅上门开卡') {
                return $this->returnMsg(103, '物流信息为空');
            }
        }

        // 拼多多发货
        $res = $douyinModel->subOrder($orderData);
        if (!empty($res)) {
            if (is_string($res)) {
                $res = json_decode($res, true);
            }
            if (!empty($res['code']) && $res['code'] == 10000) {
                DB::table('pdd_catch')->where(['dist_orderno' => $orderData['dist_orderno']])->update(['status' => '20', 'status_desc' => '已发货', 'is_delive' => 2]);
                // DB::table('douyin_catch')->where()->update(['is_delive' => 2]);
            }
        }
        return $res;
    }
}
